package com.yxp423.ssmempl.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxp423.ssmempl.bean.Overtime;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.service.IOvertimeService;
import com.yxp423.ssmempl.service.IUserService;
import com.yxp423.ssmempl.utils.consts.UserConst;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-04-24 19:51
 * @Version: 1.0
 */
@Controller
@RequestMapping("/overtime")
public class OverTimeController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IOvertimeService overtimeService;


	Cache<String, IPage> overtimePagesCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);
	Cache<String, User> overtimeUsersCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);


	@GetMapping("/applyovertime")
	public String applyOvertime() {

		return "overtime/apply_overtime";
	}

	@GetMapping("reviewovertime")
	public String toReviewOvertime() {

		return "overtime/review_overtime";
	}

	/**
	 * 页面跳转
	 *
	 * @return “我的加班”页面
	 */
	@GetMapping("myovertime")
	public String toMyOvertimePage() {


		return "overtime/my_overtime";
	}


	@GetMapping("/submitApply")
	@ResponseBody
	public AjaxResult submitApply(Overtime overtime, String name, String date, String sTime, String eTime){

		AjaxResult result = new AjaxResult();
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (user == null) {
			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}

		if (!user.getName().equals(name)) {

			result.setSuccess(false);
			result.setMsg("申请人只能是当前登录账号人");
			return result;
		}

		Date dateStartTime = DateUtil.parse(date + " " + sTime);
		Date dateEndTime = DateUtil.parse(date + " " + eTime);

		overtime.setUserId(user.getUserId().toString());
		overtime.setStartTime(dateStartTime);
		overtime.setEndTime(dateEndTime);
		overtime.setCreatTime(DateUtil.date());
		boolean dayIn = DateUtil.isIn(DateUtil.parse(date), DateUtil.beginOfMonth(new Date()), DateUtil.endOfMonth(new Date()));

		if (!dayIn) {
			result.setSuccess(false);
			result.setMsg("申请时间只能为本月");
			return result;
		}


		try {
			int flag = overtimeService.saveOvertimeApply(overtime);

			if (flag < 0) {
				result.setSuccess(false);
				result.setMsg("保存失败");


			} else {
				result.setSuccess(true);
				result.setMsg("保存成功");

			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg(e.toString());
		}

		return result;
	}


	/**
	 * 获取我的加班分页
	 *
	 * @param page
	 * @return
	 */
	@GetMapping("myapplyovertime")
	@ResponseBody
	public AjaxResult myApplyOvertime(Page page) {

		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		try {

			IPage<Overtime> myAllOvertime = overtimeService.getMyAllOvertime(user, page);

			/**
			 * 将姓名写入
			 */
			if (ObjectUtil.isNotEmpty(myAllOvertime)) {

				List<Overtime> dates = myAllOvertime.getRecords();

				for (Overtime data : dates) {

					data.setUserName(user.getName());

					User reviewer = userService.getUserById(Integer.parseInt(data.getReviewerId()));
					data.setReviewerName(reviewer.getName());
				}

				result.setSuccess(true);
				result.setData(myAllOvertime);

			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(e.toString());
		}

		return result;
	}

	@GetMapping("/myReviewOvertimes")
	@ResponseBody
	public AjaxResult myReviewOvertimes(Page page) {

		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();
		try {
			if (ObjectUtil.isNull(overtimePagesCache.get("page"+page.getCurrent()))) {


				IPage<Overtime> overtimes = overtimeService.getReviewOvertime(user, page);


				for (Overtime overtime : overtimes.getRecords()) {

					if (ObjectUtil.isNull(overtimeUsersCache.get("user"+overtime.getUserId()))){

						overtime.setReviewerName(user.getName());//审核人姓名为当前登录用户

						User userById = userService.getUserById(Integer.parseInt(overtime.getUserId()));//每次通过ID查询申请人的姓名
						overtime.setUserName(userById.getName());
						overtimeUsersCache.put("user"+overtime.getUserId(),userById);

					}else {

						overtime.setReviewerName(user.getName());//审核人姓名为当前登录用户
						overtime.setUserName(overtimeUsersCache.get("user"+overtime.getUserId()).getName());

					}

				}

				result.setSuccess(true);
				result.setMsg("获取成功");
				result.setData(overtimes);
				overtimePagesCache.put("page" + page.getCurrent(), overtimes);

			} else {

				result.setSuccess(true);
				result.setMsg("获取成功");
				result.setData(overtimePagesCache.get("page" + page.getCurrent()));

			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("系统出错，错误信息为" + e.toString());

		}

		return result;
	}


	@GetMapping("/reviewone")
	@ResponseBody
	public AjaxResult reviewOne(Overtime overtime) {
		AjaxResult result;

		result = overtimeService.saveReview(overtime);

		overtimePagesCache.clear();
		return result;

	}

}
